<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Yyou;
use app\common\model\Acct;
use app\common\model\Admin;
use app\common\model\Bank;
use app\common\model\Config;
use app\common\model\Systemconfig;
use app\common\model\User;
use app\common\model\user\Commission;
use app\common\model\user\Withdrawlog;
use fast\Random;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 提现
 */
class Withdraw extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 提现申请
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, description="提现金额")
     * @ApiParams (name="bank_id", type="string", required=false, sample="", description="银行卡id")
     * @ApiParams (name="type", type="string", required=false, sample="", description="提现方式:1=线下提现,2=用友提现")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function addWithdraw()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'type'  => 'require|number|in:1,2',
                'money'  => 'require|number|egt:1',
                'bank_id'  => 'require|gt:0',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $user = $this->auth->getUser();
        bcscale(2);
        $type = $this->request->post('type', 1);
        if ($type == 2 ) {
            $data = [
                'thirdUserId' => $this->auth->id,
                // 'mobile' => $this->auth->yy_mobile,
                'userType' => 'EMPLOYEE',
            ];
            $yyou = new Yyou($data);
            $data = $yyou->getAccountJson();
            if ($data['total'] == 0) {
                $this->responseMsg('000400', [], '账号不存在');
            } else {
                $res = (new Yyou([
                    // 'identityCode' => $this->auth->id_card,
                    // 'realName' => $this->auth->yy_name,
                    'thirdUserId' => $this->auth->id,
                    'aesId' =>  config('site.contract_id'),
                ]))->getAccountInfoJson();
                if ($res['code'] != '000000') {
                    $this->responseMsg($res['code'], [], $res['mesg']);
                }
                if ($res['data']['cardStatus'] != 1) {
                    $this->responseMsg(1, ['code' => 101], '请先绑定收款账户');
                }
                if ($res['data']['econtractStatus'] == 0) {
                    $this->responseMsg(1,  ['code' => 102], '认证审核中');
                }
                if ($res['data']['idcardStatus'] == 0) {
                    $this->responseMsg(1,  ['code' => 103], '缺少证件照');
                }
            }
        }
        $money = abs($this->request->post('money'));
        $withdraw_rate = config('site.withdraw_rate') ?? 0;
        $min_withdraw = config('site.min_withdraw') ?? 0;
        $withdraw_num = config('site.withdraw_num') ?? 0;
        $sxf = bcmul($money, $withdraw_rate);
        $count = Withdrawlog::where('status', '<', '2')->where('user_id', $this->auth->id)->whereTime('createtime', 'month')->count();
        if ($count >= $withdraw_num) {
            $this->responseMsg(1, '', '本月提现次数已满');
        }
        if ($min_withdraw && $money < $min_withdraw) {
            $this->responseMsg(1, '', '提现金额不能低于' . $min_withdraw);
        }
        $money = bcadd($money, $sxf);
        //验证金额
        if ($user->commission < $money) {
            $this->responseMsg(1, '', '可提现金额不足' . $money);
        }
        $sn = sn('user_withdrawlog', 'sn', 'TX');
        $data = [
            'user_id' => $user->id,
            'bank_id' => $this->request->post('bank_id'),
            'money' => $money,
            'tax_rate' => $sxf,
            'sn' => $sn,
            'acct_id' => $user->acct_id
        ];

        Db::startTrans();
        try {
            if ($type == 2) {
                $bank = Bank::get($this->request->post('bank_id'));
                $res = (new Yyou([
                    'demandNo' => config('site.requirement_number'),
                    'name' => $user->name,
                    'identityCode' => $user->id_card,
                    'mobile' => $user->mobile,
                    'accountBank' => $bank->cardholder,
                    'taskTarget' => '用户提现',
                    'labourFee' =>   bcsub($money, $sxf, 2),
                    'targetServiceNum' => $sn,
                    'templateParam' => json_encode([
                        'field001' => $user->name . '提现',
                        'field002' => '提现信息',
                        'field003' => date('Y-m-d H:i:s'),
                        'field004' => '标准',
                    ]),
                ]))->addTaskJson();
                //扣减佣金
                if ($res) {
                    if ($res['code'] != '000000') {
                        exception($res['mesg']);
                    }
                    $data['bourEmpNo'] = $res['data']['bourEmpNo'];
                    $data['type'] = $type;
                }
            }

            User::update(
                ['commission' => $user->commission - $money],
                ['id' => $user->id]
            );
            $log = new Withdrawlog($data);
            $log->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->responseMsg(101, '', $e->getMessage());
        }
        $this->responseMsg(0);
    }


    /**
     * @Author LK
     * @date: 2025-08-28 18:07:59
     * @ApiTitle (解绑自然人信息)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="string", required=true, description="")
     * @ApiReturn ({"code":1,"msg":"返回成功"})
     */
    public function unbindNaturalPerson()
    {

        $data = [
            'thirdUserId' => $this->auth->id,
        ];
        try {
            $yyou = new Yyou($data);
            $data = $yyou->unbindNaturalPerson();
        } catch (\Throwable $th) {
            $this->error($th->getMessage());
        }
        $this->success($data);
    }
    /**
     * @Author LK
     * @date: 2025-08-27 16:33:36
     * @ApiTitle (创建账号)
     * @ApiMethod (POST)
     * @ApiParams (name="realName", type="string", required=true, sample="", description="姓名")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="手机号")
     * @ApiReturnParams (name="code", type="string", required=true, description="")
     * @ApiReturn ({"code":1,"msg":"返回成功"})
     */
    public function createAccount()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['realName', 'require', '姓名不能为空'],
            ['mobile', 'require', '手机号不能为空'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $data = [
            'thirdUserId' => $this->auth->id,
            'mobile' => $mobile,
            'realName' => $realName,
            'enabled' => 1,
            'userType' => 'EMPLOYEE',
        ];
        try {
            $yyou = new Yyou($data);
            $data = $yyou->getAddAccountJson();
        } catch (\Throwable $th) {
            $this->error($th->getMessage());
        }
        User::update(
            ['yy_name' => $realName, 'yy_mobile' => $mobile],
            ['id' => $this->auth->id]
        );
        $this->success('创建成功', $data);
    }

    /**
     * @Author LK
     * @date: 2025-08-27 16:33:36
     * @ApiTitle (获取待办中心)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, sample="", description="ID")
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiParams (name="page", type="string", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="string", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="string", required=true, description="")
     * @ApiReturn ({"code":1,"msg":"返回成功"})
     */
    public function getCenter()
    {
        $data = [
            'thirdUserId' => $this->auth->id,
            'aesId' => config('site.contract_id'),
            'bindBank' => 1,
            'collectionAccountType' => '0'
        ];
        try {
            $yyou = new Yyou($data);
            $data = $yyou->getCenterJson();
        } catch (\Throwable $th) {
            $this->error($th->getMessage());
        }
        $this->success('', $data);
    }
    /**
     * 提现信息
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function withdrawInfo()
    {
        $user = $this->auth->getUser();
        $withdraw_num = config('site.withdraw_num') ?? 0;
        $count = Withdrawlog::where('status', '<', '2')->where('user_id', $this->auth->id)->whereTime('createtime', 'month')->count();
        $this->responseMsg(0, [
            'money' => $user->commission,
            'true_name' => $user->true_name,
            'cardno' => $user->cardno,
            'bank' => $user->bank,
            'min' => config('site.withdrawrule') ?? 0,
            'rule' => config('site.min_withdraw') ?? 0,
            
            'num' => $withdraw_num - $count
        ]);
    }

    /**
     * 提现记录
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="integer", required=true, description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function list()
    {
        $user = $this->auth->getUser();
        $res = Withdrawlog::with('bank')->where('withdrawlog.user_id', $user->id)->order('id desc')->paginate(10);
        $this->responseMsg(0, $res);
    }
}
